﻿using GetData.webProductClass;
using jutehui.GetData;
using jutehui.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace GetData
{
    public class SMZDM
    {
        /// <summary>
        /// 什么值得买 HTML信息 获取商品信息 并保存到数据库
        /// </summary>
        /// <returns></returns>
        public string GetSaleURL(string url)
        {
            //  List<Product> productList = new List<Product>();
            var productList = GetProductByRegexToHtml(url);
            if (productList == null || productList.Count < 1)
            {
                return "网络异常，未能获取数据";
            }
            // GetProductList(jsonStr, productList);//得到要插入数据库的数据
            //保存数据库
            DataTable dt = null;
            //转化成table插入
            string errorMsg = "";
            dt = CustomMethod.ListToDataTable<Product>(productList, "Product", ref errorMsg);
            if (dt == null || dt.Rows.Count < 1)
            {
                return errorMsg;
            }
            jutehui.BLL.Product bll = new jutehui.BLL.Product();
            string msg = "";

            if (bll.SaveTableData("Product", dt, out msg))
            {
                return "";
            }
            else //返回失败信息
            {
                return msg;
            }
        }

        /// <summary>
        /// 将获取的html代码经过正则获取商品信息返回
        /// </summary>
        /// <returns></returns>
        private List<Product> GetProductByRegexToHtml(string url)
        {
            ProductTypeEnum pEnum = new ProductTypeEnum();
            List<Product> productList = new List<Product>();
            string htmlText = CustomMethod.GetHtmlByHttpHelper(url);
            //获取每个商品 html数据
            string infosRegex = infosRegex = @"<div class=""list "" articleid=""(.|\s)*?"" timesort=""(.|\s)*?"" >[\s\S]*?</div>\s+<div class=""clear"">"; //href='(.*)'
            var list = CustomMethod.GetInfoByRegex(infosRegex, htmlText, 0);
            if (list == null || list.Count < 1)
            {
                CustomMethod.WriteLog("什么值得买精选，没有获取到商品信息：");
                return null;
            }
            //遍历每个商品的html 正则 解析出需要的属性值
            for (int index = 0; index < list.Count; index++)
            {
                Product product = new Product();
                //-------------------------------初始化数据------------------
                product.FromWeb = "什么值得买精选";
                product.UpdateTime = DateTime.Now;
                product.UpdateTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                try
                {
                    var herfList = CustomMethod.GetInfoFroma(list[index]);
                    if (herfList == null || herfList.Count < 1)
                    {
                        CustomMethod.WriteLog("什么值得买没有匹配到商品信息，请检查规则");
                        continue;
                    }
                    if (herfList[1] == "优惠")
                    {
                        product.TypeId = (int)MallsEnumClass.NavigationType.精选;
                    }
                    else if (herfList[1] == "海淘")
                    {
                        product.TypeId = (int)MallsEnumClass.NavigationType.海淘;
                    }
                    else
                    {
                        continue;
                    }
                    //获取商品链接
                    string currentUrl = "";
                    string productUrl = "";
                    string linkRegex = @"<div class=""botPart"">[\s\S]*?<div class=""clear"">";
                    var linkContent = CustomMethod.GetInfoByRegex(linkRegex, list[index], 0);
                    if (linkContent.Count > 0)
                    {
                        var linkList = CustomMethod.GetInfoFroma(linkContent[0]);
                        if (linkList.Count > 3)
                        {
                            currentUrl = linkList[0];
                            product.Source = linkList[3];
                        }
                    }
                    product.Plink = CustomMethod.GetEvalUrl(currentUrl, ref productUrl, GetData.CustomMethod.typeOfWeb.SMZDMFX);
                    product.Memo = productUrl;
                    if (product.Plink == "")
                    {
                        if (productUrl == "")
                        {
                            CustomMethod.WriteLog("什么值得买：没有获取到商品链接");
                        }
                        continue;
                    }
                    //图片链接
                    string imgUrl = CustomMethod.GetImgUrl(list[index], "什么值得买精选");
                    if (imgUrl == "")
                    {
                        continue;
                    }
                    product.ImgUrl = imgUrl;

                    string detailUtl = herfList[2];
                    string detailText = CustomMethod.GetHtmlByHttpHelper(detailUtl);
                    string nameAndPrice = herfList[3];
                    if (nameAndPrice.Contains("白菜特价包邮"))
                    {
                        continue;
                    }
                    //-------------------------获取商品分类--------------------------------
                    string regex = @"<span itemprop=""title"">(.*?)</span>"; 
                    product.ProductTypeId = pEnum.GetProductTypeId(detailText, regex, typeof(ProductTypeEnum.smzdmType));
                    //---------------------------------------------------------------------
                    //正则获取价格 
                    string priceRegex = @"<span class=""red"">([^<]+)</span>";
                    var pPrice = CustomMethod.GetInfoByRegex(priceRegex, nameAndPrice, 1);
                    if (pPrice != null && pPrice.Count > 0)
                    {
                        product.Price = pPrice[0];
                    }

                    //获取商品名称
                    int nameStartIndex = nameAndPrice.IndexOf("<span");
                    string name = nameAndPrice.Substring(0, nameStartIndex);
                    string nameStr = Regex.Replace(name, @"<(.[^>]*)>", "");
                    product.Pname = Regex.Replace(nameStr, @"\s+", "");
                    ////获取描述信息
                    //string desRegex = @"<p itemprop=""description"">[\s\S]*?</p>";
                    //var desList = CustomMethod.GetInfoByRegex(desRegex, detailText, 0);
                    //string description = "";
                    //if (desList == null || desList.Count < 1)
                    //{
                    //    product.Description = product.Pname;
                    //}
                    //else
                    //{
                    //    for (int count = 0; count < desList.Count; count++)
                    //    {
                    //        description += Regex.Replace(desList[count], @"<(.[^>]*)>", "") + "|||";

                    //    }
                    //    product.Description = description.Replace("&nbsp;", " ");
                    //}
                    product.Pname = System.Web.HttpUtility.HtmlEncode(product.Pname);
                   
                }
                catch (Exception ex)
                {
                    CustomMethod.WriteLog("什么值得买精选：GetProductByRegexToHtml" + ex.Message.ToString());
                    continue;
                }
                productList.Add(product);

            }
            var newList = CustomMethod.GetDistinctProdcuts(productList);
            newList.Reverse();
            return newList;
        }
    }
}
